<?php
namespace Home\Controller;
use Think\Controller;

/**
 * 教练控制
 */
class CoachController extends Controller {
	//全局变量区
	/**
	 * 布局相关
	 * list_each_page_number：每一页列表条数
	 */
	public $list_each_page_number = 5;

	//**********进入教练详情前教练列表部分**********//

	/**
	 * 教练页入口函数
	 */
	public function index(){
		$this->display();
	}

	/**
	 * 列出全部教练
	 */
	public function listAllCoach(){
		//从前端获取模糊信息
		$coach_info = $_POST['coach_name'];

		//实例化教练用户信息对象
		$coachUser = M('coach_user_view');

		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的教练条数
		$page_num = $_POST['page_num'];;  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//查询
		$result = $coachUser->limit($start_p, $e_page_num)->select();
		$resultCount = $coachUser->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['resultCount'] = $resultCount;
		$this->ajaxReturn($resultList);
	}

	/**
	 * 列出当前区下所有的教练
	 */
	public function listDistrictCoach(){
		//从前端获取地理位置信息
		$coach_location['coach_province'] = $_POST['coach_province'];
		$coach_location['coach_city'] = $_POST['coach_city'];
		$coach_location['coach_district'] = $_POST['coach_district'];

		//实例化教练对象
		$coach = M('coach_table');
		//实例化用户对象
		$user = M('user_table');

		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的教练条数
		$page_num = $_POST['page_num'];;  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//信息查询
		$coachResult = $coach->where($coach_location)->field('coach_id, coach_picture, coach_description, coach_phone')->limit($start_p, $e_page_num)->select();
		for($x1 = 0; $x1 < count($coachResult); $x1 ++){
			$coachInfo = $coachResult[$x1];
			unset($where);
			$where['id'] = $coachInfo['coach_id'];
			$userResult = $user->where($where)->field('name')->select();
			$coachResult[$x1]['name'] = $userResult;
		}
		$coachCount = $coach->where($coach_location)->count();

		//ajax返回
		$resultList['result'] = $coachResult;
		$resultList['coach_name'] = $userResult;
		$resultList['page_num'] = $page_num;
		$resultList['coach_count'] = $coachCount;
		$this->ajaxReturn($resultList);
	}

	/**
	 * 教练搜索
	 */
	public function coachSearch(){
		//从前端获取模糊信息
		$coach_info = $_POST['coach_name'];

		//实例化教练用户信息对象
		$coachUser = M('coach_user_view');

		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的教练条数
		$page_num = $_POST['page_num'];;  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//查询
		$name = "%".$coach_info;
		$where['name'] = array('like', $name."%");
		$result = $coachUser->where($where)->limit($start_p, $e_page_num)->select();
		$resultCount = $coachUser->where($where)->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['resultCount'] = $resultCount;
		$this->ajaxReturn($resultList);
	}

	/**
	 * 课程查询
	 */
	public function courseSearch(){
		//从前端获取模糊信息
		$course_info = $_POST['course_name'];

		//实例化课程信息视图对象
		$courseInfo = M('course_coach_view');

		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的教练条数
		$page_num = $_POST['page_num'];;  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//查询
		$name = "%".$course_info;
		$where['name'] = array('like', $name."%");
		$result = $courseInfo->where($where)->limit($start_p, $e_page_num)->select();
		$resultCount = $courseInfo->where($where)->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['resultCount'] = $resultCount;
		$this->ajaxReturn($resultList);
	}

	/**
	 * 列出全部课程
	 */
	public function listAllCourse(){
		//实例化课程信息视图对象
		$courseInfo = M('course_coach_view');

		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的教练条数
		$page_num = $_POST['page_num'];;  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//查询
		$result = $courseInfo->limit($start_p, $e_page_num)->select();
		$resultCount = $courseInfo->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['resultCount'] = $resultCount;
		$this->ajaxReturn($resultList);
	}

	/**
	 * 列出当前区下的课程
	 */
	public function listCourse(){
		//从前端获取地理位置信息
		$coach_location['coach_province'] = $_POST['coach_province'];
		$coach_location['coach_city'] = $_POST['coach_city'];
		$coach_location['coach_district'] = $_POST['coach_district'];

		//实例化课程信息视图对象
		$courseInfo = M('course_coach_view');

		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的教练条数
		$page_num = $_POST['page_num'];;  //页数

		//置位
		$start_p = $e_page_num * ($page_num - 1);

		//查询
		$result = $courseInfo->where($coach_location)->limit($start_p, $e_page_num)->select();
		$resultCount = $courseInfo->where($coach_location)->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['resultCount'] = $resultCount;
		$this->ajaxReturn($resultList);
	}
	
	/**
	 * 课程报名
	 * 返回值：
	 *     0：已经报名
	 *     1：报名成功
	 *     2：报名失败
	 */	
	public function applyCourse(){
		$courseId = $PSOT['course_id'];

		//实例化课程预定对象
		$courseBook = M('course_book_table');

		$resultList = array();

		$data['course_id'] = $courseId;
		$data['course_booker_id'] = session('id');

		//查询是否已经报名
		$alreadyResult = $courseBook->where($data)->find();

		if($alreadyResult){
			$resultList['result'] = 0;
		}else{
			//添加报名
			$addResult = $courseBook->add($data);
			if($addResult){
				$resultList['result'] = 1;
			}else{
				$resultList['result'] = 2;
			}
		}

		$this->ajaxReturn($resultList);
	}

	//**********进入教练详情后展示部分**********//
	/**
	 * 教练详情页面
	 */
	public function coachDetail(){
		//从前端获取教练标识
		$coach_info['coach_id'] = $_GET['coach_id'];

		//实例化教练对象
		$coach = M('coach_table');
		//实例化用户对象
		$user = M('user_table');
		//实例化课程对象
		$course = M('course_table');

		//查询教练信息
		$coachResult = $coach->where($coach_info)->find();
		$where['id'] = $coach_info['coach_id'];
		$userResult = $user->where($where)->field('name, gender, email, phone')->find();
		unset($where);
		$where['course_coach_id'] = $coach_info['coach_id'];
		$courseResult = $course->where($where)->select();

		//返回数据
		$resultList['coachResult'] = $coachResult;
		$resultList['userResult'] = $userResult;
		$resultList['courseResult'] = $courseResult;

		$this->assign('resultList', json_encode($resultList));
		$this->display();
	}

	//**********申请成为教练部分**********//

	/**
	 * 加载申请教练页
	 */
	public function applyBeCoach(){
		$this->display();
	}

	/**
	 * 申请成为教练
	 * 返回值：
	 *     字段自动检测错误：相应错误信息
	 *     添加失败：返回3
	 *     添加成功：返回0
	 *     图片上传失败：返回对应错误信息
	 */
	public function applyBeCoachHandel(){
		//实例化球会对象
		$coach = D('CoachTable');
		//实例化用户对象
		$user = M('user_table');

		// 自动验证 创建数据集
        if (!$data = $coach->create()) {
            // 防止输出中文乱码
            header("Content-type: text/html; charset=utf-8");
            $resultList['result'] = $coach->getError();
        }else{
        	//自动验证完成，接收上传图片
        	//实例化上传类
          	$upload = new \Org\Net\UploadFile();
          	$upload->maxSize = 3145728;
          	//设置文件上传类型  
          	$upload->allowExts = array('jpg','gif','png','jpeg');  
          	//设置文件上传位置  
          	//$upload->savePath = __PUBLIC__."/Img/Uploads/";
          	$upload->savePath = "./Public/Img/Uploads/coachImg/";  
          	//设置文件上传名(按照时间)  
          	$upload->saveRule = "time";
          	if (!$upload->upload()){  
              	$resultList['result'] = $upload->getErrorMsg();  
          	}else{  
              	//上传成功，获取上传信息  
              	$info = $upload->getUploadFileInfo();
              	$savename = $info[0]['savename'];
          	  	$imgurl = "__PUBLIC__/Img/Uploads/coachImg/".$savename;
          	  	$data['coach_picture'] = $imgurl;
          	  	$data['coach_id'] = session('id');

          	  	//添加球馆
        		$result = $coach->add($data);
        		if(!$result){
        			$resultList['result'] = 3;
        		}else{
        			//处理用户的access类型
        			$accessTypeOld = session('access');
        			$where['id'] = session('id');
        			if($accessTypeOld == 0){
        				session('access', 3);
        				$changeData['access'] = 3;
        				$user->where($where)->save($changeData);
        			}elseif($accessTypeOld == 1){
        				session('access', 5);
        				$changeData['access'] = 5;
        				$user->where($where)->save($changeData);
        			}elseif($accessTypeOld == 2){
        				session('access', 6);
        				$changeData['access'] = 6;
        				$user->where($where)->save($changeData);
        			}elseif($accessTypeOld == 4){
        				session('access', 7);
        				$changeData['access'] = 7;
        				$user->where($where)->save($changeData);
        			}
        			$resultList['result'] = 0;
        		}
          	}	
        }

        $this->ajaxReturn($resultList);
	}

	//**********教练管理部分**********//

	/**
	 * 列表我的课程
	 */
	public function listMyCourse(){
		//实例化课程对象
		$user=$_SESSION['think_'];
        $this->assign('user',$user);
		$course = M('course_table');
		//位置信息
		//$e_page_num = $this->list_each_page_number;  //每一页的教练条数
		//$page_num = $_POST['page_num'];;  //页数
		//置位
		//$start_p = $e_page_num * ($page_num - 1);
		//列表我的课程
		$where['course_coach_id'] = session('id');
		$result = $course->where($where)->select();
		$this->data = $result;
		//$result = $course->where($where)->limit($start_p, $e_page_num)->select();
		//$resultCount = $course->where($where)->count();
        $this->display();
	
		//ajax返回
		//$resultList['result'] = $result;
		//$resultList['page_num'] = $page_num;
		//$resultList['resultCount'] = $resultCount;
		//$this->ajaxReturn($resultList);
	}

	
	 //管理端发布课程
	public function publish_course()
	{
		$coach_id=session('id');	
		$user=$_SESSION['think_'];
        $this->assign('user',$user);
        //设置当前的选项位置（即该选项为橙色)
      $this->assign("biz_item_num",8);	
      $this->display();
	}
	//管理端
	public function publish_course_handler()
	{
		$user_id=session('id');
		$user = M('user_table');
		$access=$user->where("id=%s",$user_id)->getFIeld('access');
		/* dump($access);
		return; */
		if ($access==3 || $access==5 || $access==6 || $access==7)
		{
			$_validate = array(
        	array('course_name', 'require', '课程名称不能为空！'), 
			array('course_content', 'require', '课程描述不能为空！'), 
			array('course_contain_number', 'require', '课程总人数不能为空！'), 	
    	    );
		  $upload = new \Org\Net\UploadFile();  
          $upload->maxSize = 3145728;  
          //设置文件上传类型  
          $upload->allowExts = array('jpg','gif','png','jpeg');  
          //设置文件上传位置  
          //$upload->savePath = __PUBLIC__."/Img/Uploads/";
          $upload->savePath = "./Public/Img/Uploads/courseImg/";  
          //设置文件上传名(按照时间)  
          $upload->saveRule = "time";  
          if (!$upload->upload()){  
              $this->error($upload->getErrorMsg());  
          }else{  
              //上传成功，获取上传信息  
              $info = $upload->getuploadFileInfo();
              			  
          }
          $savename = $info[0]['savename'];
          $imgurl = "__PUBLIC__/Img/Uploads/courseImg/".$savename;
		  $data["course_name"] = $_POST["course_name"];
          //$data["activity_gymnasium"] = $_POST["activity_gymnasium"];
	      $data["course_description"] = $_POST["course_content"];
		  $data["course_schedule_st_number"]=$_POST["course_contain_number"];
		  $data["course_status"]=0;
		  $data['course_picture']=$imgurl;
		  $data["course_coach_id"]=session('id');
		  $course=M('course_table');
		  if (!$result = $course->validate($_validate)->create())
			{
				
				$this->error($course->getError());
			}
			else
			if ($course->add($data))
			{
				$this->success("添加成功");
			}
			else
			{
				 /* dump($course->getLastSql());
				return;   */
				$this->error("请正确输入球馆id");
			}
		}
		else 
		{
			$this->error("只有教练才能发布课程");
		}
	}
	/**
	 * 创建课程处理
	 * 返回值：
	 *     自动校验错误：相应错误信息
	 *     上传图像失败：相应错误信息
	 */
	public function createCourseHandel(){
		//实例化课程对象
		$course = D('CourseTableModel');

		$resultList = array();

		// 自动验证 创建数据集
        if (!$data = $course->create()) {
            // 防止输出中文乱码
            header("Content-type: text/html; charset=utf-8");
            $resultList['result'] = $course->getError();
        }else{
        	//自动验证完成，接收上传图片
        	//实例化上传类
          	$upload = new \Org\Net\UploadFile();
          	$upload->maxSize = 3145728;
          	//设置文件上传类型  
          	$upload->allowExts = array('jpg','gif','png','jpeg');  
          	//设置文件上传位置  
          	//$upload->savePath = __PUBLIC__."/Img/Uploads/";
          	$upload->savePath = "./Public/Img/Uploads/coachImg/courseImg/";  
          	//设置文件上传名(按照时间)  
          	$upload->saveRule = "time";
          	if (!$upload->upload()){  
              	$resultList['result'] = $upload->getErrorMsg();  
          	}else{  
              	//上传成功，获取上传信息  
              	$info = $upload->getUploadFileInfo();
              	$savename = $info[0]['savename'];
          	  	$imgurl = "__PUBLIC__/Img/Uploads/coachImg/courseImg/".$savename;
          	  	$data['course_picture'] = $imgurl;
          	  	$data['course_coach_id'] = session('id');
        		$data['course_status'] = 0;

        		//添加课程
        		$addResult = $course->add($data);
        		if(!$result){
        			$resultList['result'] = 1;
        		}else{
        			$resultList['result'] = 0;
        		}
          	}
        }

        $this->ajaxReturn($resultList);
	}

	/**
	 * 课程状态修改处理
	 */
	public function changeCourse(){
		//实例化课程对象
		$course = M('course_table');

		//从前端获取新的课程状态
		$data['course_status'] = $_POST['course_status'];
		//从前端获取课程id
		$where['course_id'] = $_POST['course_id'];

		$changeResult = $course->where($where)->save($data);
		if(!$changeResult){
			$resultList['result'] = 0;
		}else{
			$resultList['result'] = 1;
		}

		$this->ajaxReturn($resultList);
	}

	/**
	 * 删除课程
	 */
	public function deleteCourse(){
		//实例化课程对象
		$course = M('course_table');

		//从前端获取课程id
		$where['course_id'] = $_POST['course_id'];
		$where['course_coach_id'] = session('id');
		$status=$course->where($where)->getField('course_status');
		if ($status==0)
		{
		$resultList['msg']=$status;
		$deleteResult = $course->where($where)->delete();
		}
		else{
			$resultList['msg']=$status;
		}
		

		$this->ajaxReturn($resultList);
	}

	/**
	 * 删除教练处理
	 * 返回值：
	 *     删除失败：0
	 *     删除成功：1
	 */
	public function deleteClubHandel(){
		//实例化球馆对象
		$coach = M('club_table');
		//实例化用户对象
		$user = M('user_table');

		$userId = session('id');

		//删除教练
		$where['coach_id'] = $userId;
		$deleteResult = $club->where($where)->delete();

		if(!$deleteResult){
			$resultList['result'] = 0;
		}else{
			$accessType = session('access');
			unset($where);
			$where['id'] = session('id');
			if($accessType == 3){
				session('access', 0);
				$data['access'] = 0;
				$user->where($where)->save($data);
			}elseif($accessType == 5){
				session('access', 1);
				$data['access'] = 1;
				$user->where($where)->save($data);
			}elseif($accessType == 6){
				session('access', 2);
				$data['access'] = 2;
				$user->where($where)->save($data);
			}elseif($accessType == 7){
				session('access', 4);
				$data['access'] = 4;
				$user->where($where)->save($data);
			}

			$resultList['result'] = 1;
		}

		$this->ajaxReturn($resultList);
	}
    public function courseDetail()
	{
		$course_id=$_POST['course_id'];
		$user_id=session('id');
		$course=M('course_table');
		$result=$course->where("course_id='%d'",$course_id)->find();
		$status=$course->where("course_id='%d'",$course_id)->getField('course_status');
		$resultList["result"]=$result;
		$resultList['msg'] = $status;
		$this->ajaxReturn($resultList);
	}
	public function applyCoursePeople()
	{
		$course_id=$_POST['course_id'];
		$apply=M('course_book_table');
		$people=$apply->join('thinkphp_user_table on thinkphp_course_book_table.course_booker_id=thinkphp_user_table.id')->where("course_id='%d'",$course_id)->field('name')->select();
		$resultList["result"]=$people;
		$this->ajaxReturn($resultList);
	}
	
	public function updateCourse()
	{
		if (IS_POST) {
		  if (!session('id')) $this->error("请先登录");
		  $upload = new \Org\Net\UploadFile();  
          $upload->maxSize = 3145728;  
          //设置文件上传类型  
          $upload->allowExts = array('jpg','gif','png','jpeg');  
          //设置文件上传位置  
          //$upload->savePath = __PUBLIC__."/Img/Uploads/";
          $upload->savePath = "./Public/Img/Uploads/courseImg/";  
          //设置文件上传名(按照时间)  
          $upload->saveRule = "time";  
          if (!$upload->upload()){  
          }else{  
              //上传成功，获取上传信息  
              $info = $upload->getuploadFileInfo();
              $savename = $info[0]['savename'];
              $imgurl = "__PUBLIC__/Img/Uploads/courseImg/".$savename;
              $data['course_picture']=$imgurl;			  
          }
          
		$course=M('course_table');
		$course_id = $_POST["course_id"];
		if  ($_POST["course_name"]!=NULL)
		$data["course_name"] = $_POST["course_name"];
	  /*   if  ($_POST["course_gymnasium"]!=NULL)
        $data["course_gymnasium"] = $_POST["course_gymnasium"]; */
	    if  ($_POST["course_content"]!=NULL)
	    $data["course_description"] = $_POST["course_content"];
	    
	    if  ($_POST["course_contain_number"]!=NULL)
		$data["course_schedule_st_number"]=$_POST["course_contain_number"];

			if ($course->where("course_id='%d'",$course_id)->save($data))
			{
				$this->success("修改成功");
			}
			
		} 
	}
	

}


